package com.zjj.lbw.ai;

import org.springframework.ai.document.Document;
import org.springframework.ai.reader.TextReader;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DocumentService {

    @Value("classpath:qa.txt")
    private Resource resource;

    @jakarta.annotation.Resource
    private VectorStore vectorStore;

    public List<Document> loadText() {
        TextReader textReader = new TextReader(resource);
        List<Document> documents = textReader.get();

        ZjjTextSplitter textSplitter = new ZjjTextSplitter();
        List<Document> list = textSplitter.apply(documents);

        for (Document document : list) {
            document.getMetadata().put("author", "zjj");
            document.getMetadata().put("article_type", "blog");
        }

        vectorStore.add(list);

        return list;
    }

    public List<Document> search(String message){
        SearchRequest searchRequest = SearchRequest
                .builder()
                .query(message)
                .topK(2)
                .similarityThreshold(0.4)
                .filterExpression("author in ['zjj', 'jill'] && 'article_type' == 'blog'")
                .build();
        return vectorStore.similaritySearch(searchRequest);
    }
}
